package MyPackage;
import java.util.*;
import java.io.*;
public class Main {

	public static void main(String[] args) {
		
System.out.println("MyCMD start...");
Scanner inp=new Scanner(System.in);

	String dir;
	String mask;
	//dir="C:";
	//dir="c:\\windows\\system32";
	
	System.out.println("Exercise 1\n**Print directory**\nInput directory:");
	dir=inp.nextLine();
	printDir(dir);
	
	System.out.println("\nExercise 2\n**Print tree of directory**\nInput directory:");
	dir=inp.nextLine();
	printTree(dir);
	
	System.out.println("\nExercise 3\n**Search in a directory**\nInput directory:");
	dir=inp.nextLine();
	System.out.println("Input mask:");
	mask=inp.nextLine();
	search(mask,dir);
	

		
System.out.println("\nMyCMD stop.");
	}
	
	public static void printDir(String dir){
		File f=new File(dir);
		if(!f.exists()){
			System.out.println("Not found directory "+f.toString());
		}
		else{
		
		System.out.println(">>> "+dir);
		String[] dirList=f.list();
		
		for(int i=0;i<dirList.length;i++){
			File f1=new File(dir+File.separator+dirList[i]);
			if(!f1.isFile())System.out.println("DIR "+dirList[i]);
		}
		for(int i=0;i<dirList.length;i++){
			File f1=new File(dir+File.separator+dirList[i]);
			if(f1.isFile()) {
				printAtr(f1);
				Date d=new Date(f1.lastModified());
				System.out.println(dirList[i]+"\t| "+d+" | "+f1.getPath());
				}
			
		}
		}
	}

	public static void printAtr(File f){
		if(f.canExecute()) System.out.print("E"); else System.out.print("-");
		if(f.canRead()) System.out.print("R"); else System.out.print("-");
		if(f.canWrite()) System.out.print("W "); else System.out.print("- ");
	}
	
	public static void search(String mask, String dir){
		File f=new File(dir);
		if(!f.exists()){
			System.out.println("Not found directory "+f.toString());
		}
		else{
		System.out.println("===Search: "+mask+"===");
		String[] dirList=f.list();
		
		for(int i=0;i<dirList.length;i++){
			if(dirList[i].contains(mask)) 	System.out.println(dirList[i]);
		}
		}
	}
	
	public static void printTree(String dir){
		File f=new File(dir);
		if(!f.exists()){
			System.out.println("Not found directory "+f.toString());
		}
		else{

		String[] arrayDir=new String[255];
		int i=0;
		
		while(true){
			arrayDir[i]=dir;
			i++;
			dir=f.getParent();
			if(dir==null) break;
			f=new File(dir);
		}
		for(int j=i-1;j>=0;j--){
			dir=arrayDir[j];
			printDir(dir);
			System.out.println();	
		}
		}
	}
	
}	



